package com.r2coding.security;

import com.r2coding.constant.Constant;
import com.r2coding.entity.UsersEntity;
import com.r2coding.enums.AuthResultEnum;
import com.r2coding.exception.CustomException;
import com.r2coding.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: 98k灬
 * @since: 2022/11/01
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
@Component
@Slf4j
public class CustomUserDetailService implements UserDetailsService {
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        UsersEntity user = userService.findByUserName(name);
        if (Objects.isNull(user)) {
            log.error("user is null .");
            throw new CustomException(AuthResultEnum.AUTH_FAIL);
        }

        List<String> permissions = new ArrayList<>();
        permissions.add(Constant.ADMIN);
        user.setPermissions(permissions);
        return user;
    }
}
